package com.shop.zzh.component.jwt;

import cn.hutool.json.JSONUtil;
import com.shop.zzh.dto.ResultCode;
import com.shop.zzh.dto.ResultJson;
import com.shop.zzh.result.ResultForm;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @program: zzh
 * @description: 当访问接口没有权限时，自定义的返回结果
 * @author: zhuzh
 * @create: 2019-12-16 22:30
 **/

public class RestfulAccessDeniedHandler  implements AccessDeniedHandler {
	@Override
	public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
		//验证为未登陆状态会进入此方法，认证错误
		System.out.println("认证失败：" + e.getMessage());
		httpServletResponse.setStatus(200);
		httpServletResponse.setCharacterEncoding("UTF-8");
		httpServletResponse.setContentType("application/json; charset=utf-8");
		PrintWriter printWriter = httpServletResponse.getWriter();
		String body = ResultJson.failure(ResultCode.FORBIDDEN,e.getMessage()).toString();//禁止访问
		printWriter.write(body);
		printWriter.flush();
	}
}
